<script setup lang="ts">
import {
  MemberItem,
  BanquetItem,
  VisitItem,
} from "@/api/customer/allocate/types";
import {
  getAllocateDetails,
  getStatusPicker,
  addAllocateRecord,
  updateBanquetInfo,
  updateCustomerInfo,
} from "@/api/customer/allocate";

const emits = defineEmits(["handleQuery"]);
const dialog = reactive({
  visible: false,
  title: "",
  width: "70%",
  type: "",
});

const statusOptions = ref<DictType[]>([]);
const initStatus = async () => {
  const { data } = await getStatusPicker();
  data.unshift({ id: 0, title: "请选择跟" });
  statusOptions.value = data;
};

import { RegionVo } from "@/api/system/region/types";
import { getOpenZone } from "@/api/system/region";
const allocateId = ref(0);
// 初始化区域
const zoneOptions = ref<RegionVo[]>([]);
const initZone = async () => {
  const { data } = await getOpenZone(802);
  data.unshift({ id: 0, shortname: "请选择区域" });
  zoneOptions.value = data;
};

const customerFormRef = ref(ElForm);
const customerForm = reactive<MemberItem>({
  id: 0,
});

const banquetFormRef = ref(ElForm);
const banquetForm = reactive<BanquetItem>({});

const visitFormRef = ref(ElForm);
const visitForm = reactive<VisitItem>({
  id: 0,
  member_id: 0,
  status: 0,
  status_title: "",
  remark: "",
});

const removeZone = (item: any) => {
  if (!banquetForm.zone) return;
  const index = banquetForm.zone.findIndex((i) => i.id === item.id);
  banquetForm.zone.splice(index, 1);
};

const addZone = (value: number) => {
  if (value === 0) return;
  if (!banquetForm.zone) banquetForm.zone = [];

  if (banquetForm.zone.length >= 3) {
    ElMessage.error("最多只能选择3个区域");
    banquetForm.zone_id = 0;
    return;
  }

  // 如果已经选择了该区域，则不再添加
  if (banquetForm.zone.find((i) => i.id === value)) {
    banquetForm.zone_id = 0;
    return;
  }

  const item = zoneOptions.value.find((i) => i.id === value);
  if (item) banquetForm.zone.push(item);
  banquetForm.zone_id = 0;
};

const contacts = reactive<Contact[]>([]);
const visits = reactive<VisitItem[]>([]);
const getDetails = async (id: number) => {
  const { data } = await getAllocateDetails(id);
  Object.assign(customerForm, data.customer);
  Object.assign(banquetForm, data.banquet);
  contacts.splice(0, contacts.length, ...data.contacts);
  visits.splice(0, visits.length, ...data.visits);
};

// 动态计算contacts的类型获取手机号、微信号、座机号
const mobile = computed(() => {
  if (contacts.length > 0) {
    const mobileMatch = contacts.find((item) => item.contact_type == 1);
    console.log(mobileMatch);
    if (mobileMatch) {
      return mobileMatch.contact ? mobileMatch.contact : "";
    }
  }
  return "";
});

const wechat = computed(() => {
  if (contacts.length > 0) {
    const wechatMatch = contacts.find((item) => item.contact_type == 2);
    if (wechatMatch) {
      return wechatMatch.contact ? wechatMatch.contact : "";
    }
  }
  return "";
});

const telephone = computed(() => {
  if (contacts.length > 0) {
    const telephones = contacts.find((item) => item.contact_type == 3);
    if (telephones) {
      return telephones.contact ? telephones.contact : "";
    }
  }
  return "";
});

const sourceTitle = computed(() => {
  if (customerForm.source) {
    return customerForm.source.title ? customerForm.source.title : "";
  }
  return "";
});

const showDialog = (id: number) => {
  dialog.visible = true;
  allocateId.value = id;
  getDetails(id);
  initStatus();
  initZone();
};

const submitVisit = async () => {
  if (visitForm.status === 0) {
    ElMessage.error("请选择跟进状态");
    return;
  }

  if (!visitForm.remark) {
    ElMessage.error("请填写备注");
    return;
  }

  const valid = await visitFormRef.value.validate();
  if (!valid) return;

  const { data } = await addAllocateRecord(
    customerForm.id,
    allocateId.value,
    visitForm
  );
  if (data) {
    ElMessage.success("保存成功");
    visitForm.status = 0;
    visitForm.remark = "";
    getDetails(allocateId.value);
  }
};

const submitBanquet = async () => {
  if (!banquetForm.zone || banquetForm.zone.length === 0) {
    ElMessage.error("请选择区域");
    return;
  }

  const valid = await banquetFormRef.value.validate();
  if (!valid) return;

  const { data } = await updateBanquetInfo(
    customerForm.id,
    allocateId.value,
    banquetForm
  );
  if (data) {
    ElMessage.success("保存成功");
    getDetails(allocateId.value);
  }
};

const submitCustomerInfo = async () => {
  if (!customerForm.remark) {
    ElMessage.error("请填写备注信息");
    return;
  }

  const valid = await customerFormRef.value.validate();
  if (!valid) return;

  const { data } = await updateCustomerInfo(
    customerForm.id,
    allocateId.value,
    customerForm
  );
  if (data) {
    ElMessage.success("保存成功");
    getDetails(allocateId.value);
  }
};

const customerShareRef = ref();
const showShareDialog = () => {
  customerShareRef.value.showDialog(allocateId.value, customerForm.id);
};

defineExpose({
  showDialog,
});
</script>

<template>
  <el-drawer
    class="form-dialog"
    v-model="dialog.visible"
    :size="dialog.width"
    :show-close="false"
    :with-header="false"
  >
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>

          <div>
            <el-button
              v-hasPerm="['customer:share']"
              type="success"
              size="default"
              @click="showShareDialog"
              >分配</el-button
            >
            <el-button
              v-hasPerm="['customer:info:update']"
              type="primary"
              size="default"
              @click="submitCustomerInfo"
              >保存</el-button
            >
          </div>
        </div>
      </template>
      <el-form ref="customerFormRef" :model="customerForm" label-width="5rem">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input v-model="customerForm.fullname" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码">
              <el-input v-model="mobile" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-radio-group v-model="customerForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="来源渠道">
              <el-input v-model="sourceTitle" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="微信账号">
              <el-input v-model="wechat" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="座机号码">
              <el-input v-model="telephone" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="customerForm.remark"
                placeholder="请填写备注"
                class="fixed-rows-textarea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-row class="margin-top-10">
      <el-col :span="12">
        <el-card class="form-card margin-right-5">
          <template #header>
            <div class="card-header">
              <span>回访客户</span>
            </div>
          </template>
          <div class="card-body">
            <el-steps direction="vertical" :active="1">
              <template v-for="(item, index) in visits" :key="index">
                <el-step :title="item.status_title">
                  <template #description>
                    <div style="padding: 12px 0">
                      <div>{{ item.create_time }}</div>
                      <div>回访内容:{{ item.remark }}</div>
                    </div>
                  </template>
                </el-step>
              </template>
            </el-steps>
          </div>

          <template #footer>
            <div class="card-footer" v-hasPerm="['customer:visit:add']">
              <el-form ref="visitFormRef" :model="visitForm">
                <div class="form-line">
                  <div class="form-input">
                    <el-select
                      placeholder="跟进状态"
                      v-model="visitForm.status"
                      clearable
                    >
                      <el-option
                        v-for="item in statusOptions"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                      />
                    </el-select>
                  </div>
                  <div class="form-remark">
                    <el-input
                      v-model="visitForm.remark"
                      placeholder="请输入备注"
                      clearable
                    ></el-input>
                  </div>
                  <div class="form-item">
                    <el-button type="primary" @click="submitVisit"
                      >保存</el-button
                    >
                  </div>
                </div>
              </el-form>
            </div>
          </template>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="form-card margin-left-5">
          <template #header>
            <div class="card-header">
              <span>婚宴信息</span>
            </div>
          </template>

          <div class="card-body">
            <el-form
              ref="banquetFormRef"
              :model="banquetForm"
              label-width="5rem"
            >
              <el-form-item label="选择区域" prop="zone_id">
                <el-select
                  v-model="banquetForm.zone_id"
                  placeholder="请选择区域"
                  clearable
                  filterable
                  @change="addZone"
                >
                  <el-option
                    v-for="item in zoneOptions"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="已选区域" prop="zone">
                <el-tag
                  class="margin-right-10"
                  v-for="item in banquetForm.zone"
                  :key="item.id"
                  closable
                  @close="removeZone(item)"
                  >{{ item.shortname }}</el-tag
                >
              </el-form-item>

              <el-form-item label="预定婚期" prop="event_date">
                <el-input v-model="banquetForm.event_date" clearable></el-input>
              </el-form-item>

              <el-form-item label="预定桌数" prop="table_amount">
                <el-input
                  v-model="banquetForm.table_amount"
                  clearable
                ></el-input>
              </el-form-item>

              <el-form-item label="预算" prop="budget">
                <el-input v-model="banquetForm.budget" clearable></el-input>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <div class="card-footer">
              <el-button
                v-hasPerm="['customer:banquet:udpate']"
                type="primary"
                @click="submitBanquet"
                >保存</el-button
              >
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <customer-share ref="customerShareRef"></customer-share>
  </el-drawer>
</template>

<style lang="scss" scoped>
.margin-top-10 {
  margin-top: 10px;
}

.margin-right-5 {
  margin-right: 5px;
}

.margin-left-5 {
  margin-left: 5px;
}

.width-100 {
  width: 100%;
}

.card-body {
  height: calc(100vh - 476px);
  overflow-y: auto;
}

.fixed-rows-textarea textarea {
  height: 3em; /* 根据你的行高调整这个值 */
  overflow-y: auto;
}

.form-line {
  display: flex;
  .form-input {
    flex: 0 120px;
    margin-right: 10px;
  }
  .form-remark {
    flex: 1;
    margin-right: 10px;
  }
}

.visit-box {
  padding: 12px 0;
}
</style>
